package lew.bing.tom;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContext;

public class ServletTemplateEngineProvider implements TemplateEngineProvider {
    private ServletContext servletContext;
    private TemplateEngine templateEngine;
    private ScriptProvider scriptProvider;

    private String prefix;

    private ServletContextTemplateResolver resolver;

    public ServletTemplateEngineProvider(ServletContext servletContext) {
        this.servletContext = servletContext;
        init();
    }

    private void init() {
        final TemplateEngine templateEngine = new TemplateEngine();
        resolver =  new ServletContextTemplateResolver(servletContext);
        // 这些都放到配置文件中
        templateEngine.addTemplateResolver(resolver);
        this.templateEngine = templateEngine;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
        resolver.setPrefix(prefix);
    }

    public void setScriptRoot(String rootPath) {
        this.scriptProvider = new DefaultScriptProvider(rootPath);
        this.scriptProvider.init(servletContext);
    }

    public String getPrefix() {
        return prefix;
    }

    @Override
    public TemplateEngine engine() {
        return this.templateEngine;
    }

    @Override
    public Object loadScript(String name) {
        if (scriptProvider != null) {
            return scriptProvider.getScript(name);
        }
        return null;
    }

}
